package com.glwan.fixedassetapp.ui.home.Activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.ListableAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.ApiConstant;
import com.glwan.fixedassetapp.common.DatabaseConstant;
import com.glwan.fixedassetapp.components.SelectView;
import com.glwan.fixedassetapp.handler.ReaderResponseInterfaces;
import com.glwan.fixedassetapp.helper.KeyCodeReceiver;
import com.glwan.fixedassetapp.helper.RFIDDeviceInterface;
import com.glwan.fixedassetapp.model.RFIDTagData;
import com.glwan.fixedassetapp.ui.home.locateTag.LocateTagActivity;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.DatabaseUtil;
import com.glwan.fixedassetapp.utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class InventoryTaskScanningActivity extends AppCompatActivity implements ReaderResponseInterfaces.ResponseTagHandler, ReaderResponseInterfaces.ResponseKeyEventHandler {

    //    private SearchableSpinner mSearchableSpinner;
    private final List<String> mStrings = new ArrayList<>();
    String fdTaskId;
    RFIDDeviceInterface rfidDeviceInterface;
    List<List<String>> initParamList = new ArrayList<>();
    List<List<String>> initParamListCache = new ArrayList<>();
    Map<String, Map<String, Object>> inventoryMap = new HashMap<>();
    List<String> existData = new ArrayList<>();
    List<String> insertInventoryList = new ArrayList<>();
    List<String> insertInventoryListCache = new ArrayList<>();
    List<Map<String, Object>> insertInventoryMapList = new ArrayList<>();
    List<Map<String, Object>> insertInventoryMapListCache = new ArrayList<>();
    KeyCodeReceiver keyCodeReceiver;
    private List<Map<String, Object>> parentList = new ArrayList<>();
    private Map<String, Integer> groupTextViewMap = new HashMap<>();
    private ListView listView;
    private ListableAdapter listableAdapter;
    private int total;
    private Button btScanning;
    private SelectView selectView;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {

            if (message.what == 1) {
                insertDatabaseHandle();
            } else if (message.what == 2) {
                DatabaseUtil.deleteData(DatabaseConstant.INVENTORY_TASK_ITEM, "FD_TASK_ID = ?", new String[]{fdTaskId});
            } else if (message.what == 3) {
                insertInventoryHandle();
            }
            return false;
        }
    });

    private Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanning_layout_1);
        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);


        setTitle(getString(R.string.inventoryScanning));

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

//        View tvMore = findViewById(R.id.tvMore);

//        tvMore.setOnClickListener(view -> {
//            CommonUtil.toastShow(getActivity(), (String) tvMore.getText(),CommonUtil.SUCCESS,true);
//
//        });


        btScanning = findViewById(R.id.btScanning);

        fdTaskId = getIntent().getStringExtra("fdId");

        rfidDeviceInterface = RFIDDeviceInterface.getInstance(Build.BRAND, this);

        btScanning.setOnClickListener(view -> {
            inventory();
        });

        Button btConfirmUpload = findViewById(R.id.btConfirmUpload);

        btConfirmUpload.setOnClickListener(view -> {
            if (getString(R.string.stopScanning).contentEquals(btScanning.getText())) {
                CommonUtil.toastShow(getActivity(), "未停止盘点时，无法进行数据上传", CommonUtil.ERROR, true);
                return;
            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("fdTaskId", fdTaskId);
            JsonArray jsonArray = new JsonArray();

            //查询结果
            String[] columnNames = new String[]{
                    "FD_YZ_CARD_ID",
                    "REASON",
                    "STATUS"};
            Cursor cursor = DatabaseUtil.querySQL(
                    DatabaseConstant.INVENTORY_TASK_ITEM,
                    columnNames,
                    "FD_TASK_ID = ? AND STATUS != 0",
                    new String[]{fdTaskId});
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("fdTaskId", fdTaskId);
            while (cursor.moveToNext()) {
                JsonObject itemJson = new JsonObject();
                for (String s : columnNames) {
                    int columnIndex = cursor.getColumnIndex(s);
                    if (columnIndex >= 0) {

                        String objectName = DatabaseUtil.convertName(s);
                        String value = cursor.getString(columnIndex);

                        if ("fdYzCardId".equals(objectName)) {
                            itemJson.addProperty("fdCardId", value);
                            continue;
                        }
                        itemJson.addProperty(objectName, value);

                    }
                }
                jsonArray.add(itemJson);
            }
            jsonObject.add("cardList", jsonArray);
            Log.i("requestData", jsonObject.toString());
            requestData(ApiConstant.UPDATE_BATCH_STATUS, jsonObject);
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        View dialogView = getLayoutInflater().inflate(R.layout.more_dialog, null);
//        builder.setView(dialogView);
        builder.setTitle("菜单列表").setIcon(R.drawable.more_function).setItems(new String[]{"物资列表"}, (dialog, which) -> {
            if (which == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("fdTaskId", fdTaskId);
                CommonUtil.startActivity(getApplicationContext(), ProductActivity.class, map, true);
            }
        });
        AlertDialog alertDialog = builder.create();

        View tvMore = findViewById(R.id.tvMore);
        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.show();
            }
        });


//        List<String> spinnerValueList = new ArrayList<>();
//        spinnerValueList.add("选项1");
//        spinnerValueList.add("选项2");
//        spinnerValueList.add("选项3");
//        selectView = findViewById(R.id.selectView);
//        selectView.setAdapter(new ArrayAdapter<>(
//                getActivity(),
//                R.layout.support_simple_spinner_dropdown_item,
//                spinnerValueList
//        ));

        initData();

    }

    private void startInventory() {
        String manufacturer = Build.MANUFACTURER;

        RFIDDeviceInterface.getInstance(manufacturer, getActivity()).startInventory();
    }

    private void initData() {

        //-------inventory_task_scanning_item_1-------
        groupTextViewMap.put("sortNo", R.id.sortNo);
        groupTextViewMap.put("fdYzCardName", R.id.fdYzCardName);
        groupTextViewMap.put("fdYzCardId", R.id.fdYzCardId);
//        groupTextViewMap.put("fdPdId", R.id.fdPdId);
        groupTextViewMap.put("status", R.id.status);

        //-------inventory_task_scanning_item_2-------
//        groupTextViewMap.put("fdYzCardCode",R.id.fdYzCardCode);
//        groupTextViewMap.put("fdYzCardName",R.id.fdYzCardName);
//        groupTextViewMap.put("fdYzCardId", R.id.fdYzCardId);
//        groupTextViewMap.put("fdSize",R.id.fdSize);
//        groupTextViewMap.put("fdCardCategoryName",R.id.fdCardCategoryName);
//        groupTextViewMap.put("fdLocation", R.id.fdLocation);
//        groupTextViewMap.put("fdDutyDeptName", R.id.fdDutyDeptName);
//        groupTextViewMap.put("fdDutyPersonName", R.id.fdDutyPersonName);

        listView = findViewById(R.id.scanList);

        listableAdapter = new ListableAdapter(
                getActivity(),
                parentList,
                groupTextViewMap,
                R.layout.inventory_task_scanning_item_1);
        listView.setAdapter(listableAdapter);

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> item = (Map<String, Object>) listableAdapter.getItem(i);
                map.put("tagPatternValue", item.get("fdYzCardId").toString().toUpperCase());
                CommonUtil.startActivity(getApplicationContext(), LocateTagActivity.class, map, true);
                return true;
            }
        });

//        Map<String, Object> map = new HashMap<>();
//        map.put("fdTaskId", fdTaskId);

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fdTaskId", fdTaskId);
        requestData(ApiConstant.GET_TASK_DETAIL_LIST, jsonObject);

//        requestTestData();

//        initCondition();
    }

    /**
     * 初始化筛选条件的值
     */
    private void initCondition() {
        List<String> spinnerValueList = new ArrayList<>();

        String[] columnNames = new String[]{"FD_LOCATION"};

        Cursor cursor = DatabaseUtil.queryDistinctSQL(DatabaseConstant.INVENTORY_TASK_ITEM, columnNames, "FD_TASK_ID = ?", new String[]{fdTaskId});
        spinnerValueList.add("全部");
        while (cursor.moveToNext()) {
            String string = cursor.getString(0);
            if (string != null && !"".equals(string) && !"null".equals(string)) {
                spinnerValueList.add(cursor.getString(0));
            }
        }


        selectView = findViewById(R.id.selectView);
        selectView.setAdapter(new ArrayAdapter<>(
                getActivity(),
                R.layout.support_simple_spinner_dropdown_item,
                spinnerValueList
        ));
        selectView.setSelectedItem(0);
    }

    private void requestTestData() {

        String result = "{\"success\":true,\"data\":{\"docNumber\":\"\",\"docCreateTime\":\"\",\"docSubject\":\"\",\"fdTaskTime\":\"\",\"fdUnit\":\"\",\"fdAssignPerson\":\"\",\"cardList\":[{\"fdPdId\":\"180abc123456daf321456780\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456780\",\"fdYzCardName\":\"资产1\",\"fdYzCardCode\":\"100000001\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456781\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456781\",\"fdYzCardName\":\"资产2\",\"fdYzCardCode\":\"100000002\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456782\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456782\",\"fdYzCardName\":\"资产3\",\"fdYzCardCode\":\"100000003\",\"fdSize\":\"10\",\"fdLocation\":\"3098室\",\"fdCardCategoryName\":\"类别2\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456783\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456783\",\"fdYzCardName\":\"资产4\",\"fdYzCardCode\":\"100000004\",\"fdSize\":\"10\",\"fdLocation\":\"3098室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3098室\",\"fdDutyPersonName\":\"吴某某\"},{\"fdPdId\":\"180abc123456daf321456784\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456784\",\"fdYzCardName\":\"资产5\",\"fdYzCardCode\":\"100000005\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"吴某某\"},{\"fdPdId\":\"180abc123456daf321456785\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456785\",\"fdYzCardName\":\"资产6\",\"fdYzCardCode\":\"100000006\",\"fdSize\":\"10\",\"fdLocation\":\"3098室\",\"fdCardCategoryName\":\"类别2\",\"fdDutyDeptName\":\"3098室\",\"fdDutyPersonName\":\"吴某某\"},{\"fdPdId\":\"180abc123456daf321456786\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456786\",\"fdYzCardName\":\"资产7\",\"fdYzCardCode\":\"100000007\",\"fdSize\":\"10\",\"fdLocation\":\"3097室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3097室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456787\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456787\",\"fdYzCardName\":\"资产8\",\"fdYzCardCode\":\"100000008\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别3\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456788\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456788\",\"fdYzCardName\":\"资产9\",\"fdYzCardCode\":\"100000009\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"冯某某\"},{\"fdPdId\":\"180abc123456daf321456789\",\"fdTaskId\":\"1234\",\"fdYzCardId\":\"180abc123456daf321456789\",\"fdYzCardName\":\"资产10\",\"fdYzCardCode\":\"100000010\",\"fdSize\":\"10\",\"fdLocation\":\"3096室\",\"fdCardCategoryName\":\"类别1\",\"fdDutyDeptName\":\"3096室\",\"fdDutyPersonName\":\"陈某某\"}]}}";
//        JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
//
//        JsonObject data = jsonObject.get("data").getAsJsonObject();
//
//        JsonArray cardList = data.get("cardList").getAsJsonArray();
//        if(cardList.size() > 0){
////                            message.what = 2;
////                            handler.sendMessage(message);
//            DatabaseUtil.deleteData(DatabaseConstant.INVENTORY_TASK_ITEM,"FD_TASK_ID = ?",new String[]{fdTaskId});
//
//        }
//        for(int i = 0 ; i < cardList.size() ; i++){
//            Map map = new Gson().fromJson(cardList.get(i), Map.class);
////            parentList.add(map);
//            if(map != null) {
//                insertDatabase(map);
//            }
//        }
//        if(initParamList.size() > 0){
//            Log.i("insertDatabase","最后直接处理");
////            Message message = new Message();
////            message.what = 1;
////            handler.sendMessage(message);
//            insertDatabaseHandle();
//        }
//        String[] columnNames = new String[]{"FD_PD_ID", "FD_YZ_CARD_NAME","FD_LOCATION"};
//        Cursor cursor = DatabaseUtil.querySQL(DatabaseConstant.INVENTORY_TASK_ITEM, columnNames, "FD_TASK_ID = ?", new String[]{fdTaskId});
//        while(cursor.moveToNext()){
//            Map<String, Object> map = new HashMap<>();
//
//            for(String s : columnNames){
//                int columnIndex = cursor.getColumnIndex(s);
//                if(columnIndex >= 0 ) {
//                    map.put(DatabaseUtil.convertName(s), cursor.getString(columnIndex));
//                }
//            }
//            int fdPdIdIndex = cursor.getColumnIndex("FD_PD_ID");
//            if(fdPdIdIndex >= 0) {
//                inventoryMap.put(cursor.getString(fdPdIdIndex), map);
//            }
//        }
//        Log.i("inventoryMap", inventoryMap.toString());


        JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
        if (jsonObject.get("success").getAsBoolean()) {
            JsonObject data = jsonObject.get("data").getAsJsonObject();

            JsonArray cardList = data.get("cardList").getAsJsonArray();
//                        JsonArray cardList = new Gson().fromJson(data.get("cardList").getAsString(), JsonArray.class);
            fdTaskId = "1234";
            Message message = new Message();
            if (cardList.size() > 0) {
//                            message.what = 2;
//                            handler.sendMessage(message);
                DatabaseUtil.deleteData(DatabaseConstant.INVENTORY_TASK_ITEM, "FD_TASK_ID = ?", new String[]{fdTaskId});

            }
            for (int i = 0; i < cardList.size(); i++) {
                Map resultMap = new Gson().fromJson(cardList.get(i), Map.class);
//                            parentList.add(resultMap);
                insertDatabase(resultMap);
            }
            if (initParamList.size() > 0) {
//                            Log.i("insertDatabase","最后直接处理");
//                            message.what = 1;
//                            handler.sendMessage(message);
                insertDatabaseHandle();
            }

            //查询结果
            String[] columnNames = new String[]{"FD_YZ_CARD_ID", "FD_YZ_CARD_NAME", "FD_LOCATION"};
            Cursor cursor = DatabaseUtil.querySQL(DatabaseConstant.INVENTORY_TASK_ITEM, columnNames, "FD_TASK_ID = ?", new String[]{fdTaskId});
            while (cursor.moveToNext()) {
                Map<String, Object> map = new HashMap<>();

                for (String s : columnNames) {
                    int columnIndex = cursor.getColumnIndex(s);
                    if (columnIndex >= 0) {
                        map.put(DatabaseUtil.convertName(s), cursor.getString(columnIndex));
                    }
                }
                int fdYzCardId = cursor.getColumnIndex("FD_YZ_CARD_ID");
                if (fdYzCardId >= 0) {
                    inventoryMap.put(cursor.getString(fdYzCardId).toUpperCase(), map);
                }
            }
            Log.i("inventoryMap", inventoryMap.toString());
//                        runOnUiThread(()-> listableAdapter.notifyDataSetChanged());
        }
//        else {
//            CommonUtil.toastShow(getActivity(), jsonObject.get("msg").getAsString(), CommonUtil.ERROR, true);
//        }
        initCondition();

    }

    /**
     * 获取数据
     *
     * @param jsonObject
     */
    private void requestData(String url, JsonObject jsonObject) {

        //打开加载框
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));

        if (ApiConstant.UPDATE_BATCH_STATUS.equals(url)) {

            //分页获取订单
            OkHttpUtil.post(url, new HashMap<>(), jsonObject, new Callback() {
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String result = response.body().string();

                    JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
                    if (jsonObject.get("success").getAsBoolean()) {
                        CommonUtil.toastShow(getActivity(), jsonObject.get("msg").getAsString(), CommonUtil.SUCCESS, true);
                    } else {
                        CommonUtil.toastShow(getActivity(), jsonObject.get("msg").getAsString(), CommonUtil.ERROR, true);
                    }
                    //关闭加载框
                    CommonUtil.cancelProgressDialog(getActivity());

                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    CommonUtil.toastShow(getActivity(), e.getMessage(), CommonUtil.ERROR, true);
                    //关闭加载框
                    CommonUtil.cancelProgressDialog(getActivity());
                }

            });
        } else if (ApiConstant.GET_TASK_DETAIL_LIST.equals(url)) {
            OkHttpUtil.post(url, new HashMap<>(), jsonObject, new Callback() {
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String result = response.body().string();

                    JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
                    if (jsonObject.get("success").getAsBoolean()) {
                        CommonUtil.toastShow(getActivity(), jsonObject.get("msg").getAsString(), CommonUtil.SUCCESS, true);
                        JsonObject data = jsonObject.get("data").getAsJsonObject();

                        JsonArray cardList = data.get("cardList").getAsJsonArray();
//                        JsonArray cardList = new Gson().fromJson(data.get("cardList").getAsString(), JsonArray.class);

                        Message message = new Message();
                        if (cardList.size() > 0) {
//                            message.what = 2;
//                            handler.sendMessage(message);
                            DatabaseUtil.deleteData(DatabaseConstant.INVENTORY_TASK_ITEM, "FD_TASK_ID = ?", new String[]{fdTaskId});

                        }
                        for (int i = 0; i < cardList.size(); i++) {
                            Map resultMap = new Gson().fromJson(cardList.get(i), Map.class);
//                            parentList.add(resultMap);
                            insertDatabase(resultMap);
                        }
                        if (initParamList.size() > 0) {
//                            Log.i("insertDatabase","最后直接处理");
//                            message.what = 1;
//                            handler.sendMessage(message);
                            insertDatabaseHandle();
                        }

                        //查询结果
                        String[] columnNames = new String[]{"FD_YZ_CARD_ID", "FD_YZ_CARD_NAME", "FD_LOCATION"};
                        Cursor cursor = DatabaseUtil.querySQL(DatabaseConstant.INVENTORY_TASK_ITEM, columnNames, "FD_TASK_ID = ?", new String[]{fdTaskId});
                        while (cursor.moveToNext()) {
                            Map<String, Object> map = new HashMap<>();

                            for (String s : columnNames) {
                                int columnIndex = cursor.getColumnIndex(s);
                                if (columnIndex >= 0) {
                                    map.put(DatabaseUtil.convertName(s), cursor.getString(columnIndex));
                                }
                            }
                            int fdYzCardId = cursor.getColumnIndex("FD_YZ_CARD_ID");
                            if (fdYzCardId >= 0) {
                                inventoryMap.put(cursor.getString(fdYzCardId).toUpperCase(), map);
                            }
                        }
                        Log.i("inventoryMap", inventoryMap.toString());
//                        runOnUiThread(()-> listableAdapter.notifyDataSetChanged());
                    } else {
                        CommonUtil.toastShow(getActivity(), jsonObject.get("msg").getAsString(), CommonUtil.ERROR, true);
                    }
                    initCondition();
                    //关闭加载框
                    CommonUtil.cancelProgressDialog(getActivity());

                }

                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    CommonUtil.toastShow(getActivity(), e.getMessage(), CommonUtil.ERROR, true);
                    //关闭加载框
                    CommonUtil.cancelProgressDialog(getActivity());
                }

            });
        }
    }

    private void insertDatabase(Map<String, String> map) {

        List<String> initParams = new ArrayList<>();
        //-------inventory_task_scanning_item_1-------
//        initParams.add(map.get("fdPdId").toUpperCase());
//        initParams.add(fdTaskId);
//        initParams.add(map.getOrDefault("fdYzCardName", ""));
//        initParams.add(map.getOrDefault("fdYzCardId", ""));
//        initParams.add(map.getOrDefault("fdLocation", ""));

        //-------inventory_task_scanning_item_2-------
        initParams.add(map.get("fdPdId"));
        initParams.add(fdTaskId);
        initParams.add(map.getOrDefault("fdYzCardId", ""));
        initParams.add(map.getOrDefault("fdYzCardName", ""));
        initParams.add(map.getOrDefault("fdYzCardCode", ""));
        initParams.add(map.getOrDefault("fdSize", ""));
        initParams.add(map.getOrDefault("fdLocation", ""));
        initParams.add(map.getOrDefault("fdCardCategoryName", ""));
        initParams.add(map.getOrDefault("fdDutyDeptName", ""));
        initParams.add(map.getOrDefault("fdDutyPersonName", ""));
        initParams.add(map.getOrDefault("status", "0"));
        initParams.add(map.getOrDefault("reason", ""));

        initParamList.add(initParams);

        if (initParamList.size() >= 100) {
//            insertDatabaseHandle();
            Log.i("insertDatabaseHandle", "每一百条处理一次");
//            Message message = new Message();
//            message.what = 1;
//            handler.sendMessage(message);
            insertDatabaseHandle();
        }

    }

    //插入数据库处理
    private void insertDatabaseHandle() {

        initParamListCache.addAll(initParamList);

        initParamList.clear();

        List<String> initColumnList = new ArrayList<>();

        //-------inventory_task_scanning_item_1-------
//        initColumnList.add("fdPdId");
//        initColumnList.add("fdTaskId");
//        initColumnList.add("fdYzCardName");
//        initColumnList.add("fdYzCardId");
//        initColumnList.add("fdLocation");

        //-------inventory_task_scanning_item_2-------
        initColumnList.add("fdPdId");
        initColumnList.add("fdTaskId");
        initColumnList.add("fdYzCardId");
        initColumnList.add("fdYzCardName");
        initColumnList.add("fdYzCardCode");
        initColumnList.add("fdSize");
        initColumnList.add("fdLocation");
        initColumnList.add("fdCardCategoryName");
        initColumnList.add("fdDutyDeptName");
        initColumnList.add("fdDutyPersonName");
        initColumnList.add("status");
        initColumnList.add("reason");

        DatabaseUtil.batchInsert(DatabaseConstant.INVENTORY_TASK_ITEM, initColumnList, initParamListCache);

        initParamListCache.clear();

    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void handleResponse(RFIDTagData data) {
        String epc = data.getEpc();
//        epc = "1884B9123ADAADD62F9043542B583FEB";
        //不存在处理
        if (!existData.contains(epc)) {
            if (inventoryMap.containsKey(epc)) {
//                Map<String, Object> map = inventoryMap.get(epc);
//                map.put("status", "已盘");

                Map<String, Object> map = inventoryMap.get(epc);
                String selectedItem = String.valueOf(selectView.getSelectTextValue());

                if ("全部".equals(selectedItem)) {
                    map.put("status", "已盘");
                } else {

                    if (!map.getOrDefault("fdLocation", "").equals(selectedItem)) {
                        map.put("status", "位置错误（盘点地点：" + selectedItem + "）");
                    } else {
                        map.put("status", "已盘");
                    }
                }
                parentList.add(map);
                Log.i("handleResponse", map.toString());
                existData.add(epc);
                runOnUiThread(() -> {
                    listableAdapter.notifyDataSetChanged();

//                    insertInventoryList.add(finalEpc);
                    insertInventoryMapList.add(map);


                    if (insertInventoryList.size() >= 100) {
                        Log.i("handleResponse", "每100条处理一次");
                        Message message = new Message();
                        message.what = 3;
                        handler.sendMessage(message);
                    }

                });
            }


        }
    }

    private void insertInventoryHandle() {

//        StringBuilder sb = new StringBuilder();
//
//        insertInventoryListCache.addAll(insertInventoryList);
//        insertInventoryList.clear();
//
//        int size = insertInventoryListCache.size();
//
//        if(size > 0) {
//            sb.append("(");
//            for (int i = 0; i < size; i++) {
//                String s = insertInventoryListCache.get(i);
//                sb.append("'").append(s).append("'");
//                if (!(i == size - 1)) {
//                    sb.append(",");
//                }
//            }
//            sb.append(")");
//            ContentValues contentValues = new ContentValues();
//            contentValues.put("STATUS", "4");
//            contentValues.put("REASON", "已盘");
//            Log.i("insertInventoryHandle", "更新任务条目" + sb.toString() +"状态");
//
////
//            int i = DatabaseUtil.updateData(DatabaseConstant.INVENTORY_TASK_ITEM, contentValues, "FD_TASK_ID = ? AND FD_PD_ID IN " + sb.toString(), new String[]{fdTaskId});
//            Log.i("insertInventoryHandle", "更新任务条目成功条数" + i);
//
//            insertInventoryListCache.clear();
//
//        }

        //加入缓存中
        insertInventoryMapListCache.addAll(insertInventoryMapList);
        insertInventoryMapList.clear();

        if (insertInventoryMapListCache.size() > 0) {
            //已盘条目的List
            List<String> countedIdList = new ArrayList<>();

            //异常盘点条目的List
            List<String> errorCountedIdList = new ArrayList<>();


            String selectedItem = String.valueOf(selectView.getSelectTextValue());
            //盘点到的数据放入insertInventoryMapCache
            for (Map<String, Object> map : insertInventoryMapListCache) {

                String status = String.valueOf(map.get("status"));

                if ("已盘".equals(status)) {
                    countedIdList.add(String.valueOf(map.get("fdYzCardId")));
//                } else if ("位置错误".equals(status)) {
                } else {
                    errorCountedIdList.add(String.valueOf(map.get("fdYzCardId")));
                }

            }
            int countedIdListSize = countedIdList.size();

            if (countedIdListSize > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append("(");
                for (int i = 0; i < countedIdListSize; i++) {
                    String s = countedIdList.get(i);
                    sb.append("'").append(s).append("'");
                    if (!(i == countedIdListSize - 1)) {
                        sb.append(",");
                    }
                }
                sb.append(")");
                ContentValues contentValues = new ContentValues();
                contentValues.put("STATUS", "4");
                contentValues.put("REASON", "");
                updateSqlHandle(countedIdList, contentValues, sb.toString());
            }

            int errorCountedIdListSize = errorCountedIdList.size();

            if (errorCountedIdList.size() > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append("(");
                for (int i = 0; i < errorCountedIdListSize; i++) {
                    String s = errorCountedIdList.get(i);
                    sb.append("'").append(s).append("'");
                    if (!(i == errorCountedIdListSize - 1)) {
                        sb.append(",");
                    }
                }
                sb.append(")");
                ContentValues contentValues = new ContentValues();
                contentValues.put("STATUS", "5");
                contentValues.put("REASON", "位置错误（盘点地点：" + selectedItem + "）");
                updateSqlHandle(errorCountedIdList, contentValues, sb.toString());
            }

        }
    }

    /**
     * 更新语句处理
     *
     * @param list          list
     * @param contentValues contentValues
     */
    private void updateSqlHandle(List<String> list, ContentValues contentValues, String ids) {
        int size = list.size();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        for (int i = 0; i < size; i++) {
            String s = list.get(i).toLowerCase();
            stringBuilder.append("'").append(s).append("'");
            if (!(i == size - 1)) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")");
        Log.i("insertInventoryHandle", "更新任务条目" + stringBuilder.toString() + "状态");

        int i = DatabaseUtil.updateData(DatabaseConstant.INVENTORY_TASK_ITEM, contentValues, "FD_TASK_ID = ? AND FD_YZ_CARD_ID IN " + ids, new String[]{fdTaskId});

//        int i = DatabaseUtil.updateData(DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, contentValues, " FD_ID IN " + stringBuilder.toString(), null);
        Log.i("更新成功条数", String.valueOf(i));
    }

    @Override
    public void handleResponse() {
        inventory();
    }

    private void inventory() {
        if (getString(R.string.startScanning).equals(btScanning.getText().toString())) {
            btScanning.setText(getString(R.string.stopScanning));
            rfidDeviceInterface.changeInventoryMode(0, null);
            rfidDeviceInterface.startInventory();
        } else {
            btScanning.setText(getString(R.string.startScanning));
            rfidDeviceInterface.stopInventory();
//            insertInventoryHandle();
            Message message = new Message();
            message.what = 3;
            handler.sendMessage(message);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        keyCodeReceiver = KeyCodeReceiver.getInstance(this);
        keyCodeReceiver.registerKeyCodeReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (rfidDeviceInterface != null)
            rfidDeviceInterface.stopInventory();
        if (keyCodeReceiver != null)
            keyCodeReceiver.unregisterReceiver();
        btScanning.setText(getString(R.string.startScanning));
    }

    @Override
    protected void onStart() {
        super.onStart();
        rfidDeviceInterface = RFIDDeviceInterface.getInstance(Build.BRAND, this);
//        rfidDeviceInterface.changeInventoryMode(0, null);
//        CommonUtil.toastShow(this, "onStart", CommonUtil.SUCCESS, true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

